import { resolve } from 'node:path'
import { readFile, writeFile } from 'node:fs/promises'
import fg from 'fast-glob'
import { svgToURL, trimSVG } from '@iconify/utils'

const rootFolder = process.cwd()
const iconsFolder = resolve(rootFolder, '.vitepress/theme/icons')
const cssFolder = resolve(rootFolder, '.vitepress/theme')

async function generateIconsCSS() {
    // Find icons
    /** @type {string[]} */
    const icons = await fg('*.svg', { cwd: iconsFolder, deep: 1 })

    // Generate CSS
    const css = ['// DO NOT EDIT THIS FILE IT IS AUTOGENERATED', ':root {']
    for (let i = 0; i < icons.length; i++) {
        const filename = icons[i]
        if (filename.startsWith('_') || filename.startsWith('.'))
            continue

        const varName = `--icon-${filename.replace('.svg', '')}`
        const content = await readFile(iconsFolder + '/' + filename, 'utf8')
        const url = svgToURL(trimSVG(content))
        css.push(`\t${varName}: ${url};`)
    }
    css.push('}')

    // Write CSS
    await writeFile(cssFolder + '/_icons.scss', css.join('\n'), 'utf8')
}

await generateIconsCSS()
